<template>
   <div class="home">
     <div class="header">
       <div class="left-action">
         <h1 @click="refresh">坐标拾取器</h1>
         <Input search enter-button="查询" :placeholder="placeholderText" size="large" class="search" v-model="searchValue" @on-search="searchText"/>
         <div class="switch-action">
           <span>坐标反查：</span>
           <i-switch v-model="isSearchLocation" size="large">
             <span slot="open">开启</span>
             <span slot="close">关闭</span>
           </i-switch>
         </div>
       </div>
       <div class="right-action">
         <CheckboxGroup v-model="showMaps">
           <Checkbox label="高德"></Checkbox>
           <Checkbox label="百度"></Checkbox>
           <Checkbox label="腾讯"></Checkbox>
           <Checkbox label="谷歌"></Checkbox>
         </CheckboxGroup>
         <Button type="primary" shape="circle" @click="reset">重置布局</Button>
       </div>
     </div>
     <div class="container">
       <Split v-model="split" @on-move-end="splitMove">
         <div slot="left" style="height: 100%;overflow:hidden;">
           <Split v-model="splitLeft" @on-move-end="splitMove">
             <div slot="left" style="height: 100%;overflow:hidden;" v-show="hasAmap">
               <div class="top-title">高德地图</div>
               <div class="info" @mouseover="hideAmapInfo">
                   <input type="text" class="input" :value="selectedAmapPosition.lng !=='' ? (selectedAmapPosition.lng + ',' + selectedAmapPosition.lat) : ''">
                   <button class="btn" @click="copy(selectedAmapPosition.lng + ',' + selectedAmapPosition.lat)">复制</button>
                 </div>
               <div id="amap" class="amap">
                 高德地图加载中...
                 <div class="position" :style="{ 'left': currentAmapLeft + 'px', 'top': currentAmapTop + 'px' }">
                   <span>{{amapCurrentPosition.lng + ',' + amapCurrentPosition.lat}}</span>
                 </div>
               </div>
             </div>
             <div slot="right" style="height: 100%;overflow:hidden;" v-show="hasBaiDu">
               <div class="top-title">百度地图</div>
               <div class="info">
                 <input type="text" class="input" :value="selectedBmapPosition.lng !=='' ? (selectedBmapPosition.lng + ',' + selectedBmapPosition.lat) : ''">
                 <button class="btn" @click="copy(selectedBmapPosition.lng + ',' + selectedBmapPosition.lat)">复制</button>
               </div>
               <div class="position" :style="{ 'left': currentBmapLeft + 'px', 'top': currentBmapTop + 'px' }">
                 <span>{{baiduMapCurrentPosition.lng + ',' + baiduMapCurrentPosition.lat}}</span>
               </div>
               <div id="baidu-map" class="baidu-map">
                 百度地图加载中...
               </div>
             </div>
           </Split>
         </div>
         <div slot="right" style="height: 100%;overflow:hidden;">
           <Split v-model="splitRight" @on-move-end="splitMove">
             <div slot="left" style="height: 100%;overflow:hidden;" v-show="hasQQ">
               <div class="top-title">腾讯地图</div>
               <div class="info">
                 <input type="text" class="input" :value="selectedQmapPosition.lng !=='' ? (selectedQmapPosition.lng + ',' + selectedQmapPosition.lat) : ''">
                 <button class="btn" @click="copy(selectedQmapPosition.lng + ',' + selectedQmapPosition.lat)">复制</button>
               </div>
               <div class="position" :style="{ 'left': currentQmapLeft + 'px', 'top': currentQmapTop + 'px' }">
                 <span>{{qqMapCurrentPosition.lng + ',' + qqMapCurrentPosition.lat}}</span>
               </div>
               <div id="qq-map" class="qq-map">
                 腾讯地图加载中...
               </div>
             </div>
             <div slot="right" style="height: 100%;overflow:hidden;" v-show="hasGoogle">
               <div class="top-title">谷歌地图</div>
               <div class="info">
                 <input type="text" class="input" :value="selectedGoolgeMapPosition.lng !=='' ? (selectedGoolgeMapPosition.lng + ',' + selectedGoolgeMapPosition.lat) : ''">
                 <button class="btn" @click="copy(selectedGoolgeMapPosition.lng + ',' + selectedGoolgeMapPosition.lat)">复制</button>
               </div>
               <div class="position" :style="{ 'left': currentGoogleLeft + 'px', 'top': currentGoogleTop + 'px' }">
                 <span>{{googleMapCurrentPosition.lng + ',' + googleMapCurrentPosition.lat}}</span>
               </div>
               <div id="google-map" class="google-map">
                 谷歌地图加载中...
               </div>
             </div>
           </Split>
         </div>
       </Split>
     </div>
   </div>
 </template>
 
 <script>
 export default {
   name: 'home',
   data () {
     return {
       split: 0.5,
       splitLeft: 0.5,
       splitRight: 0.5,
       isSearchLocation: false,
       showMaps: ['百度','腾讯','高德','谷歌'],
       amap: null,
       baiduMap: null,
       qqMap: null,
       googleMap: null,
       amapCurrentPosition: { // 高德地图当前鼠标位置
         lng: '',
         lat: ''
       },
       currentAmapLeft: -200,
       currentAmapTop: -200,
       selectedAmapPosition: {
         lng: '',
         lat: ''
       },
       selectedBmapPosition: {
         lng: '',
         lat: ''
       },
       baiduMapCurrentPosition: { // 百度地图当前鼠标位置
         lng: '',
         lat: ''
       },
       currentBmapLeft: -200,
       currentBmapTop: -200,
       searchValue: '',
       qqMapCurrentPosition: {
         lng: '',
         lat: ''
       },
       currentQmapLeft: -200,
       currentQmapTop: -200,
       selectedQmapPosition: {
         lng: '',
         lat: ''
       },
       qmapMarkerList: [],
       currentGoogleLeft: -200,
       currentGoogleTop: -200,
       selectedGoolgeMapPosition: {
         lng: '',
         lat: ''
       },
       googleMapCurrentPosition: { // 谷歌地图当前鼠标位置
         lng: '',
         lat: ''
       },
     }
   },
   props: {
     msg: String
   },
   computed: {
     placeholderText () {
       if (this.isSearchLocation) {
         return 'lng,lat'
       } else {
         return '请输入名称...'
       }
     },
     hasQQ () {
       return this.showMaps.indexOf('腾讯') > -1
     },
     hasBaiDu () {
       return this.showMaps.indexOf('百度') > -1
     },
     hasAmap () {
       return this.showMaps.indexOf('高德') > -1
     },
     hasGoogle () {
       return this.showMaps.indexOf('谷歌') > -1
     }
   },
   created () {   
     window.amapInit = () => {
     }
     window.baiduMapInit = () => {
     }
     window.qqMapInit = () => {
     }
     window.googleMapInit = () => {
       try {
        this.initGoogleMap() 
       } catch (error) {
         console.log(error)
       }
     }
   },
   mounted () {
     let str = localStorage.getItem('splitValue')
     if (str) {
       let { split, splitLeft, splitRight } = JSON.parse(str)
       this.split = split
       this.splitLeft = splitLeft
       this.splitRight = splitRight
     }
     this.initAmap()
     this.initQqMap()
     this.initBaiduMap()
   },
   methods: {
     splitMove () {
       let obj = {
         split: this.split,
         splitLeft: this.splitLeft,
         splitRight: this.splitRight,
       }
       localStorage.setItem('splitValue', JSON.stringify(obj))
     },
     // 重置布局
     reset () {
       this.$Modal.confirm({
         title: '提示',
         content: '<p>重置之后布局变为初始的四等分，</p><p>确认要重置吗？</p>',
         onOk: () => {
           this.split = 0.5
           this.splitLeft = 0.5
           this.splitRight = 0.5
           if (localStorage.getItem('splitValue')) {
             localStorage.removeItem('splitValue')
           }
           this.$Message.info('布局已重置');
         },
         onCancel: () => {
         }
       });
     },
     refresh () {
       let url = window.location.href
       window.location.href = url
     },
     // 初始化高德地图
     initAmap () {
       var map = new window.AMap.Map('amap', {
        center:[116.397541,39.906939],
        zoom:11
       });
       this.amap = map
       // this.amap.plugin('AMap.Geolocation', () => {
       //   let geolocation = new window.AMap.Geolocation({
       //       enableHighAccuracy: true,//是否使用高精度定位，默认:true
       //       timeout: 10000,          //超过10秒后停止定位，默认：无穷大
       //       maximumAge: 0,           //定位结果缓存0毫秒，默认：0
       //       convert: true,           //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
       //       showButton: true,        //显示定位按钮，默认：true
       //       buttonPosition: 'LB',    //定位按钮停靠位置，默认：'LB'，左下角
       //       buttonOffset: new window.AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
       //       showMarker: true,        //定位成功后在定位到的位置显示点标记，默认：true
       //       showCircle: true,        //定位成功后用圆圈表示定位精度范围，默认：true
       //       panToLocation: true,     //定位成功后将定位到的位置作为地图中心点，默认：true
       //       zoomToAccuracy:true      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
       //   });
       //   this.amap.addControl(geolocation);
       //   geolocation.getCurrentPosition();
       // })
       this.amap.on('mousemove', this.showAmapPosition)
       this.amap.on('click', (e) => {
         this.selectedAmapPosition = {
           lng: e.lnglat.lng,
           lat: e.lnglat.lat
         }
       })
     },
 
     showAmapPosition (e) {
       this.amapCurrentPosition = {
         lng: e.lnglat.lng,
         lat: e.lnglat.lat
       }
       this.currentAmapLeft = e.pixel.x + 10
       this.currentAmapTop = e.pixel.y + 20
     },
     hideAmapInfo () {
       this.currentAmapLeft = -200
       this.currentAmapTop = -200
     },
     // 初始化百度地图
     initBaiduMap () {
       var map = new window.BMap.Map("baidu-map");
       map.centerAndZoom(new window.BMap.Point(116.072775,39.914174), 11);
       map.enableScrollWheelZoom(true)
       map.addEventListener('click', (e) => {
         this.selectedBmapPosition = {
           lng: e.point.lng,
           lat: e.point.lat
         }
       })
       map.addEventListener('mousemove', (e) => {
         this.showBmapPosition(e)
       })
       this.baiduMap = map
     },
     showBmapPosition (e) {
       this.baiduMapCurrentPosition = {
         lng: e.point.lng,
         lat: e.point.lat
       }
       this.currentBmapLeft = e.offsetX + 10
       this.currentBmapTop = e.offsetY + 20
     },
     // 初始化腾讯地图
     initQqMap () {
       var map = new window.qq.maps.Map(document.getElementById("qq-map"), {
         center: new window.qq.maps.LatLng(39.913283,116.403932),
         zoom:11,
         mapTypeControl: true, // 地图类型控件
         zoomControl: true, // 缩放控件
         panControl: true // 平移控件
       });
       window.qq.maps.event.addListener(map, 'click', (e) => {
         this.selectedQmapPosition = {
           lng: e.latLng.lng,
           lat: e.latLng.lat
         }
       })
       window.qq.maps.event.addListener(map, 'mousemove', (e) => {
         this.showQmapPosition(e)
       })
       this.qqMap = map
     },
     showQmapPosition (e) {
       this.qqMapCurrentPosition = {
         lng: e.latLng.lng,
         lat: e.latLng.lat
       }
       this.currentQmapLeft = e.cursorPixel.x + 10
       this.currentQmapTop = e.cursorPixel.y + 20
     },
     // 初始化谷歌地图
     initGoogleMap () {
       var map = new window.google.maps.Map(document.getElementById("google-map"), {
         center: {lat: 39.90628552519536, lng: 116.39750252981538},
         zoom: 11
       });
       map.addListener("click", (e) => {
         this.selectedGoolgeMapPosition = {
           lng: e.latLng.toJSON().lng,
           lat: e.latLng.toJSON().lat
         }
       })
       window.google.maps.event.addListener(map, 'mousemove', (e) => {
         this.showGoogleMapPosition(e)
       })
       this.googleMap = map
     },
     showGoogleMapPosition (e) {
       this.googleMapCurrentPosition = {
         lng: e.latLng.toJSON().lng,
         lat: e.latLng.toJSON().lat
       }
       this.currentGoogleLeft = e.pixel.x + 10
       this.currentGoogleTop = e.pixel.y + 20
     },
     searchText () {
       if (this.searchValue !== '') {
         if (this.isSearchLocation) { // 坐标反查
           if (this.searchValue.indexOf(',') > -1) {
             this.amapPositionSearch(this.searchValue)
             this.bmapPositionSearch(this.searchValue)
             this.qmapPositionSearch(this.searchValue)
             this.googlePositionSearch(this.searchValue)
           } else {
             this.$Message.error({
               content: '输入格式错误！'
             })
           }
         } else { // 关键字搜索
           this.amapTextSearch(this.searchValue)
           this.bmapTextSearch(this.searchValue)
           this.qmapTextSearch(this.searchValue)
         }
       } else {
         this.$Message.error({
           content: '输入为空！'
         })
       }
     },
     amapTextSearch (text) {
       this.amap.clearMap()
       window.AMap.service(["AMap.PlaceSearch"], () => {
         //构造地点查询类
         var placeSearch = new window.AMap.PlaceSearch({ 
             pageSize: 999, // 单页显示结果条数
             pageIndex: 1, // 页码
             citylimit: false,  //是否强制限制在设置的城市内搜索
             map: this.amap, // 展现结果的地图实例
             autoFitView: true // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
         });
         //关键字查询
         placeSearch.search(text, (e) => {
           if (e === 'no_data') {
             this.$Message.error({
               content: '高德地图查询无结果！'
             })
           }
         });
       });
     },
     amapPositionSearch (text) {
       this.amap.clearMap()
       let lng = text.split(',')[0]
       let lat = text.split(',')[1]
       let marker = new window.AMap.Marker({
         position: new window.AMap.LngLat(lng, lat),
         icon: 'https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png'
       })
       this.amap.add(marker)
       this.amap.panTo(new window.AMap.LngLat(lng, lat))
     },
     bmapTextSearch (text) {
       this.baiduMap.clearOverlays()
       let myGeo = new window.BMap.Geocoder()
       myGeo.getPoint(text, (point) => {
         if (point) {
           this.baiduMap.centerAndZoom(point, 16)
           this.baiduMap.addOverlay(new window.BMap.Marker(point))
         }else{
           this.$Message.error({
             content: '百度地图查询无结果！'
           })
         }
       }, "中国")
     },
     bmapPositionSearch (text) {
       this.baiduMap.clearOverlays()
       let lng = text.split(',')[0]
       let lat = text.split(',')[1]
       let point = new window.BMap.Point(lng, lat)
       let marker = new window.BMap.Marker(point)
       this.baiduMap.addOverlay(marker)
       this.baiduMap.centerAndZoom(point, 16)
     },
     qmapTextSearch (text) {
       this.qmapDeleteAllMarker()
       let searchService = new window.qq.maps.SearchService({
         complete: (results) => {
           //设置回调函数参数
           var pois = results.detail.pois;
           var infoWin = new window.qq.maps.InfoWindow({
               map: this.qqMap
           });
           var latlngBounds = new window.qq.maps.LatLngBounds();
           for (var i = 0, l = pois.length; i < l; i++) {
               var poi = pois[i];
               latlngBounds.extend(poi.latLng);
               ((n) => {
                 var marker = new window.qq.maps.Marker({
                     map: this.qqMap
                 });
                 marker.setPosition(pois[n].latLng);
                 marker.setTitle(i + 1);
                 this.qmapMarkerList.push(marker);
                 window.qq.maps.event.addListener(marker, 'click', () => {
                   infoWin.open();
                   infoWin.setContent('<div style="width:280px;height:100px;">' + 'POI的ID为：' + pois[n].id + '，POI的名称为：' + pois[n].name + '，POI的地址为：' + pois[n].address + '，POI的类型为：' + pois[n].type + '</div>');
                   infoWin.setPosition(pois[n].latLng);
                 });
               })(i);
           }
           this.qqMap.fitBounds(latlngBounds);
         },
         error: function() {
           this.$Message.error({
             content: '腾讯地图查询无结果！'
           })
         }
       });
       searchService.setPageIndex(1);
       searchService.setPageCapacity(999);
       searchService.search(text);
     },
     qmapPositionSearch (text) {
       this.qmapDeleteAllMarker()
       let lng = text.split(',')[0]
       let lat = text.split(',')[1]
       //地址和经纬度之间进行转换服务
       let geocoder = new window.qq.maps.Geocoder();
       //设置服务请求成功的回调函数
       geocoder.setComplete((result) => {
         console.log('result', result)
           this.qqMap.setCenter(result.detail.location);
           var marker = new window.qq.maps.Marker({
               map: this.qqMap,
               position: result.detail.location
           });
           this.qmapMarkerList.push(marker)
           //点击Marker会弹出反查结果
           window.qq.maps.event.addListener(marker, 'click', () => {
               alert("坐标地址为： " + result.detail.location);
           });
       });
       //若服务请求失败，则运行以下函数
       geocoder.setError((err) => {
         console.log(err)
           alert("出错了，请输入正确的地址！！！");
       });
       geocoder.getAddress(new window.qq.maps.LatLng(parseFloat(lat).toFixed(6), parseFloat(lng).toFixed(6)));
     },
     googlePositionSearch (text) {
     //   console.log('this.googleMap', this.googleMap)
     //   this.googleMap.clearMap()
       let lng = text.split(',')[0]
       let lat = text.split(',')[1]
       let point = {
         lat,
         lng
       }
       var marker = new window.google.maps.Marker({
           map: this.googleMap,
           position: point
       });
       console.log(marker)
       this.googleMap.setCenter(point)
       this.googleMap.setZoom(15)
     },
     qmapDeleteAllMarker () {
       if (this.qmapMarkerList.length > 0) {
         this.qmapMarkerList.forEach(marker => {
           marker.setMap(null)
         })
         this.qmapMarkerList = []
       }
     },
     copy (val) {
       let transfer = document.createElement('input');
       document.body.appendChild(transfer);
       transfer.value = val  // 这里表示想要复制的内容
       transfer.focus();
       transfer.select();
       if (document.execCommand('copy')) {
           document.execCommand('copy');
       }
       transfer.blur();
       this.$Message.success({
         content: '复制成功！'
       })
       document.body.removeChild(transfer);
     }
   }
 }
 </script>
 
 <style lang="less" scoped>
 .home {
   width: 100%;
   height: 100%;
   background: #E5ECF9;
   .header {
     width: 100%;
     height: 80px;
     background-color: white;
     display: flex;
     justify-content: space-between;
     align-items: center;
     padding: 0 50px;
     .left-action {
       display: flex;
       justify-content: space-between;
       align-items: center;
       .switch-action {
         margin-left: 20px;
       }
       .search {
         width: 500px;
       }
       h1 {
         margin-right: 50px;
         &:hover {
           cursor: pointer;
         }
       }
       @media all and (-webkit-min-device-pixel-ratio:0) and (min-resolution: .001dpcm) { 
       h1 {
         background-image: -webkit-linear-gradient(left, #147B96, #E6D205 25%, #147B96 50%, #E6D205 75%, #147B96);
         -webkit-text-fill-color: transparent;
         -webkit-background-clip: text;
         -webkit-background-size: 200% 100%;
         -webkit-animation: masked-animation 4s infinite linear;
       }
       }
       @-webkit-keyframes masked-animation {
           0%  { background-position: 0 0;}
           100% { background-position: -100% 0;}
       }
     }
     .right-action {
       display: flex;
       justify-content: flex-start;
       align-items: center;
     }
   }
 }
 .container {
   height: calc(100% - 80px);
   width: 100%;
   .left {
     z-index: 0;
     overflow: hidden;
   }
   .right {
     z-index: 1;
     overflow: hidden;
   }
   .top-title {
     width: 100%;
     height: 30px;
     display: flex;
     justify-content: center;
     align-items: center;
     font-size: 18px;
     font-weight: 600;
     color: red;
   }
   .info {
     .input {
       width: 80%;
       margin-right: 5px;
     }
     .btn {
       &:hover {
         cursor: pointer;
       }
     }
     width: 200px;
     height: 50px;
     bottom: 30px;
     right: 0;
     position: absolute;
     z-index: 1;
     display: flex;
     justify-content: center;
     align-items: center;
   }
   .position {
     // min-width: 150px;
     // max-width: 300px;
     width: fit-content;
     min-height: 30px;
     background-color: white;
     position: absolute;
     z-index: 2;
     color: black;
     font-weight: 600;
     padding: 5px 8px;
     box-sizing: border-box;
   }
   .amap, .baidu-map, .qq-map, .google-map {
     width: 100%;
     height: calc(100% - 20px);
     top: 0;
     left: 0;
   }
 }
 </style>
 